// pages/bargain/bargain.js
var app = getApp();
const getPageInfoUrl = '/Bargain/index';
const getBargainListUrl = '/Bargain/bargainList';
const getRuleUrl = '/Bargain/rule';
const shareSuccessUrl = '/Bargain/shareSuccess';
const helpCutPriceUrl = '/Bargain/helpBargain';
const selfBargainUrl = '/Bargain/selfBargain';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    displayAuthShow: 0,//控制授权弹层的显示和隐藏
    user_nick: '',//用户昵称
    user_image: '',//用户头像
    service_bargain_detail_is_show:0,//客服ico是否显示
    service_content: '',//客服描述
    service_reply_btn_title: '',//客服按钮文案
    is_kf_mask_show: 0,//控制客服弹层的显示
    is_axe_show:1,//控制神斧按钮的显示
    isLoading:1,//是否显示加载中
    user_level:0,//用户的身份
    is_not_enough:0,//判断神斧数量是否足够
    num:0,//神斧个数
    guide: {}, //引导盒子文案
    adv_info: [], //页面顶部专题列表
    static_url_http: '', //资源文件地址
    // is_bargain:0,//判断是否为砍价商品
    recommendList: [], //商品推荐列表
    page: 1, //商品推荐页码
    goodsId: 0, //商品ID
    cash: {}, //赠送给好友的优惠券信息
    self_share_num: '', //自己给自己分享的次数
    is_group: 0, //判断分享的是否为群
    encryptedData: '', //分享的参数
    iv: '', //分享的参数
    shareTitle: '', //分享的标题
    sharePath: '', //分享的路径
    shareImg: '', //分享的图片
    ruleList: [], //规则列表
    countDownDay: '00', //倒计时的天数
    countDownHour: '00', //倒计时的小时数
    countDownMinute: '00', //倒计时的分钟数
    countDownSecond: '00', //倒计时的秒数
    self_bargain_num: 0, //自己砍掉的次数
    other_bargain_num: 0, //他人砍掉的次数
    bargainList: [], //砍价榜列表
    bargainListPage: 1, //砍价榜页面
    user_avatar: '', //用户头像地址
    user_nick: '', //用户昵称
    goods_img: '', //商品图片
    goods_name: '', //商品标题
    original_price: 0.00, //商品原价
    buy_price: 0.00, //商品优品价
    get_num: 0, //已领取的人数
    bargain_user_help_btn_title: '', //好友刚进入页面的按钮文案
    bargain_user_suceess_title: '', //帮助好友砍价成功文案
    bargain_help_btn_title: '', //好友进入页面按钮文案
    bargain_help_btn_title: '', //自己进入页面邀请好友砍一刀按钮文案
    bargain_suceess_title: '', //砍价成功的文案
    bargain_self_one_one_title: '', //自己砍价成功描述的文案第一行
    bargain_self_one_two_title: '', //自己砍价成功描述的文案第二行
    bargain_share_btn_title: '', //自己砍价弹层按钮的文案
    axe_num_not_enough_one_title:'',//神斧数量不足弹层文案第一行
    axe_num_not_enough_two_title: '',//神斧数量不足弹层文案第二行
    self_bargain_money: '', //自己砍价的金额
    other_bargain_money: '', //好友砍价的金额
    bargain_get_goods_title: '', //帮好友砍价成功按钮文案
    sub_money: '', //已砍金额
    residue_money: '', //剩余要砍金额
    total_money: '', //总共需要砍的金额
    end_time: '', //订单结束的时间戳
    is_end: 0, //判断是否已经结束
    scheduleWidth: 0, //进度条宽度
    order_id: 0, //订单ID
    share_uid: 0, //分享者ID
    isfriendShareMaskShow: 0, //控制好友分享成功的弹层
    isfriendCutMaskShow: 0, //控制好友砍价成功弹层的显示
    isSelfShareMaskShow: 0, //控制自己分享成功弹层的显示
    isSelfCutMaskShow: 0, //控制自己砍价成功弹层的显示
    isResultMaskShow: 0, //控制规则弹层的显示
    winWidth: 0, //手机屏幕的宽度
    winHeight: 0, //手机屏幕的高度
  },
  // 关闭客服弹层
  closeKfmask: function () {
    this.setData({
      is_kf_mask_show: 0
    });
  },
  // 打开客服弹层
  openKfmask: function () {
    this.setData({
      is_kf_mask_show: 1
    });
  },
  // 用神斧砍一刀
  selfBargain:function(e){
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    if (_this.data.num==0){
      _this.setData({
        isSelfCutMaskShow: 1,
        is_not_enough:1
      })
    }else{
      var requestData = {
        token: _this.data.token,
        version: app.setConfig.version,
        type: app.setConfig.type,
        order_id: _this.data.order_id,
        uid: _this.data.share_uid
      }
      app.post(selfBargainUrl, requestData, function (res) {
        if (res.code == 2000) {
          _this.setData({
            self_bargain_money:res.data.self_bargain_money,
            num: res.data.num,
            user_level:res.data.level,
            sub_money: res.data.sub_money,
            residue_money: res.data.residue_money,
            isSelfCutMaskShow:1
          });
          _this.calculateScheduleWidth();
        }else{
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      })
    }
    
  },
  // 判断是否为空对象
  isEmptyObject: function(obj) {
    for (var key in obj) {
      return true
    };
    return false
  },
  // 跳转会员页
  goVip: function(e) {
    var formId = e.detail.formId;
    app.postFormId(this.data.token, formId);
    wx.navigateTo({
      url: '/pages/vipRecharge/vipRecharge',
    })
  },
  // 点击顶部导航跳转广告详情
  jumpDetail: function(e) {
    var advType = e.currentTarget.dataset.type_detail;
    console.log(advType);
    if (advType.adv_type == 3) {
      wx.navigateToMiniProgram({
        appId: advType.app_id.toString(),
        path: advType.page.toString(),
        extraData: advType.sence.toString(),
        complete(res) {
          console.log(res)
        }
      });
    } else if (advType.adv_type == 4) {
      var subject_id = advType.adv_id;
      wx.navigateTo({
        url: '/' + advType.adv_uri + '?subject_id=' + subject_id,
      })
    }
  },
  // 跳转我的现金券页面
  goCouponList: function() {
      this.setData({
        isfriendShareMaskShow: 0
      })
    wx.navigateTo({
      url: '/pages/couponList/couponList',
    })
  },
  // 跳转商品详情页
  goGoodsDetail: function(e) {
    var formId = e.detail.formId;
    app.postFormId(this.data.token, formId);
    console.log(e);
    wx.navigateTo({
      url: '/pages/goodsDetail/goodsDetail?goodsId=' + e.currentTarget.dataset.goods_id,
    })
  },
  // 跳转订单详情页
  goOrderDetail: function(e) {
    var formId = e.detail.formId;
    app.postFormId(this.data.token, formId);
    wx.navigateTo({
      url: '/pages/orderDetail/orderDetail?orderId=' + this.data.order_id,
    })
  },
  // 获取页面信息
  getPageInfo: function() {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      order_id: _this.data.order_id,
      uid: _this.data.share_uid
    }
    app.post(getPageInfoUrl, requestData, function(res) {
      if (res.code == 2000) {
        var configs = wx.getStorageSync('configs');
        var sub_adv = res.data.sub_adv;
        for (var i = 0; i < sub_adv.length; i++) {
          sub_adv[i].adv_info_url = configs.static_url_http + '/' + sub_adv[i].adv_info_url
        }
        var guide = res.data.guide;
        console.log(_this.isEmptyObject(guide));
        if(_this.isEmptyObject(guide)){
          guide.isShow = 1;
        }else{
          guide.isShow = 0;
        }
        _this.setData({
          user_nick: configs.user_nick,
          user_image: configs.user_image,
          service_bargain_detail_is_show: configs.service_bargain_detail_is_show,
          service_content: configs.service_content,
          service_reply_btn_title: configs.service_reply_btn_title,
          isLoading:0,
          user_level: res.data.level,
          num: res.data.num,
          guide: res.data.guide,
          adv_info: sub_adv,
          adv_solt: res.data.adv,
          user_nick: res.data.user_nick,
          user_avatar: res.data.image,
          goods_img: configs.static_url_http + '/' + res.data.goods_img,
          axe_num_not_enough_one_title:configs.axe_num_not_enough_one_title,
          axe_num_not_enough_two_title: configs.axe_num_not_enough_two_title,
          goods_name: res.data.goods_name,
          original_price: res.data.original_price,
          buy_price: res.data.buy_price,
          get_num: res.data.get_num,
          bargain_get_goods_title: res.data.bargain_get_goods_title,
          bargain_help_btn_title: res.data.bargain_help_btn_title,
          bargain_user_suceess_title: res.data.bargain_user_suceess_title,
          bargain_suceess_title: res.data.bargain_suceess_title,
          sub_money: res.data.sub_money,
          residue_money: res.data.residue_money,
          total_money: res.data.total_money,
          is_axe_show: res.data.is_axe_show,
          is_self: res.data.is_self,
          end_time: res.data.end_time,
          is_end: res.data.is_end,
          self_bargain_num: res.data.self_bargain_num,
          other_bargain_num: res.data.other_bargain_num,
          bargain_self_one_one_title: res.data.bargain_self_one_one_title,
          bargain_self_one_two_title: res.data.bargain_self_one_two_title,
          bargain_share_btn_title: res.data.bargain_share_btn_title,
          self_bargain_money: res.data.self_bargain_money,
          other_bargain_money: res.data.other_bargain_money,
          shareTitle: res.data.share.title,
          sharePath: res.data.share.page,
          shareImg: res.data.share.image,
          bargain_user_help_btn_title: res.data.bargain_user_help_btn_title,
          share_uid: res.data.uid,
          order_id: res.data.order_id,
          goodsId: res.data.goods_id
        })
        _this.calculateScheduleWidth();
        _this.getBargainList();
        _this.getRecommendList();
        if (res.data.is_end == 0) {
          _this.bargainCountDown();
          if (res.data.is_self == 1) {
            if (res.data.self_bargain_num == 1) {
              _this.setData({
                isSelfCutMaskShow: 1
              })
            }
          } else {
            if (res.data.other_bargain_num == 1) {
              _this.setData({
                isfriendCutMaskShow: 1
              })
            }
          }
        }
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  // 计算进度条宽度
  calculateScheduleWidth: function() {
    var sub_money = this.data.sub_money;
    var total_money = this.data.total_money;
    var scheduleWidth = Math.floor(sub_money / total_money * 100) + '%';
    this.setData({
      scheduleWidth: scheduleWidth
    })
  },
  // 获取砍价榜信息
  getBargainList: function() {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      bargain_page: _this.data.bargainListPage,
      uid: _this.data.share_uid,
      order_id: _this.data.order_id
    }
    app.post(getBargainListUrl, requestData, function(res) {
      if (res.code == 2000) {
        var bargainList = _this.data.bargainList;
        bargainList = bargainList.concat(res.data.bargain_list);
        var bargainListHeight;
        if (bargainList.length < 2) {
          bargainListHeight = 'auto'
        } else {
          bargainListHeight = '240rpx';
        }
        _this.setData({
          bargainListHeight: bargainListHeight,
          bargainListPage: res.data.bargain_page,
          bargainList: bargainList
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  // 获取砍价规则
  getRule: function() {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
    }
    app.post(getRuleUrl, requestData, function(res) {
      if (res.code == 2000) {
        _this.setData({
          ruleList: res.data.rule_list
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  // 获取商品推荐列表
  getRecommendList: function() {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      keywords: _this.data.goods_name,
      recommend_type: 1,
      search_type: 0,
      page: _this.data.page
    }
    app.post('/Goods/recommend', requestData, function(res) {
      if (res.code == 2000) {
        wx.hideNavigationBarLoading(); //完成停止加载
        wx.stopPullDownRefresh(); //停止下拉刷新
        var recommendList = _this.data.recommendList;
        var configs = wx.getStorageSync('configs');
        for (var i = 0; i < res.data.list.length; i++) {
          res.data.list[i].img = configs.static_url_http + '/' + res.data.list[i].img;
        }
        recommendList = recommendList.concat(res.data.list);
        _this.setData({
          static_url_http: configs.static_url_http,
          page: res.data.page,
          recommendList: recommendList
        })
      }else{
        wx.showToast({
          title: res.msg,
          icon: "none",
          duration: 2000
        });
      }
    });
  },
  // 关闭好友分享成功弹层
  closefriendShareMask: function() {
    var _this = this;
    _this.setData({
      isfriendShareMaskShow: 0
    });
  },
  // 关闭好友砍价成功的弹层
  closefriendCutMask: function() {
    var _this = this;
    _this.setData({
      isfriendCutMaskShow: 0
    });
  },
  // 关闭自己分享成功的弹层
  closeSelfShareMask: function() {
    var _this = this;
    // console.log("点");
    _this.setData({
      isSelfShareMaskShow: 0
    });
  },
  // 关闭自己砍价成功的弹层
  closeSelfCutMask: function() {
    var _this = this;
    // console.log("点");
    _this.setData({
      isSelfCutMaskShow: 0
    });

  },
  // 关闭规则弹层
  closeRuleMask: function() {
    var _this = this;
    _this.setData({
      isResultMaskShow: 0
    });
  },
  ruleEntrance: function() {
    var _this = this;
    _this.setData({
      isResultMaskShow: 1
    });
  },
  /*红包广告跳转事件*/
  goAdvEvent: function(e) {
    var _this = this;
    var adv_solt = _this.data.adv_solt;
    if (_this.data.adv_solt) {
      //广告数据不为空
      if (adv_solt.adv_type == 1) {
        //图片类
        wx.navigateTo({
          url: '/pages/rule/rule?url=' + adv_solt.adv_info_url
        });
      } else if (adv_solt.adv_type == 3) {
        //小程序类
        wx.navigateToMiniProgram({
          appId: adv_solt.app_id.toString(),
          path: adv_solt.page.toString(),
          extraData: adv_solt.sence.toString(),
          complete(res) {
          }
        });
      } else {
        //内部网页类型
        wx.navigateTo({
          url: "/" + adv_solt.adv_uri,
        })
      }
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var _this = this;
    wx.getSystemInfo({
      success: function(res) {
        _this.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        })
      }
    });
    _this.setData({
      order_id: options.order_id
    })
    if (options.uid) {
      _this.setData({
        share_uid: options.uid
      })
    }
    app.checkAuthioze(success => {
      _this.loop();
    }, fail => {
      //未授权提示用户授权
      _this.setData({
        displayAuthShow: 1
      });
    });
  },
  /*角色权限控制*/
  getUserInfo: function (e) {
    var that = this;
    var infoUser = e.detail.userInfo;
    var res = e.detail;
    var url = app.setConfig.url + '/Login/doLogin';
    that.setData({
      displayAuthShow: 0,
      isGetInfo: 1
    });
    var data = {
      user_name: infoUser.nickName,
      nick_name: infoUser.nickName,
      head_img: infoUser.avatarUrl,
      sex: infoUser.gender,
      coutry: infoUser.country,
      city: infoUser.city,
      province: infoUser.province,
      code: app.globalData.code,
      encryptedData: res.encryptedData,
      signature: res.signature,
      ctype: app.setConfig.type,
      version: app.setConfig.version,
      iv: res.iv,
    }
    app.postLogin(url, data, function () {
      var cash = wx.getStorageSync('cash');
      if (cash != "") {
        that.setData({
          displayAuthShow: 0,
          isfriendShareMaskShow: 1,
          cash: cash
        })
      }
      that.loop();
      wx.navigateBack({
        delta: 1,
      })
    });
  },
  authRest: function () {
    this.setData({
      displayAuthShow: 0
    });
    setTimeout(function () {
      wx.reLaunch({
        url: '/pages/bargain/bargain',
      })
    }, 1000)
  },
  // 判断是否获取到token的值了
  loop: function() {
    var _this = this;
    var theToken = wx.getStorageSync("token");
    var theRegionUnit = _this.data.regionUnit;
    if (!theToken) {
      setTimeout(function() {
        _this.loop()
      }, 100);
    } else {
      _this.setData({
        token: theToken
      });
      _this.getPageInfo();
      _this.getRule();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.calculateScheduleWidth();
    wx.showShareMenu({
      withShareTicket: true,
      success: function(res) {
        console.log('参数', res);
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(e) {
    var _this = this;
    var is_mask = 0;
    
    if (typeof (e.target)!='undefined'){
      console.log(typeof (e));
      console.log(e);
      is_mask = e.target.dataset.is_mask;
    }
    
    _this.setData({
      isfriendShareMaskShow: 0, //控制好友分享成功的弹层
      isfriendCutMaskShow: 0, //控制好友砍价成功弹层的显示
      isSelfShareMaskShow: 0, //控制自己分享成功弹层的显示
      isSelfCutMaskShow: 0, //控制自己砍价成功弹层的显示
      isResultMaskShow: 0, //控制规则弹层的显示
    })
    _this.shareSuccessEvent(is_mask);
    return {
      title: _this.data.shareTitle,
      path: _this.data.sharePath,
      imageUrl: _this.data.shareImg,
      success: function(res) {
      }
      
    }
   
  },
  // 砍价分享成功事件
  shareSuccessEvent: function(isMask) {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      order_id: _this.data.order_id,
      uid: _this.data.share_uid,
      is_btn: isMask
    }
    app.post(shareSuccessUrl, requestData, function(res) {
      if (res.code == 2000) {
        console.log(_this.data.sharePath);
        var isSelfShareMaskShow;
        if (res.data.self_share_num == 1) {
          isSelfShareMaskShow = 1
        } else {
          isSelfShareMaskShow = 0
        }
        if (res.data.is_self == 1) {
          _this.setData({
            is_self: res.data.is_self,
            self_bargain_money: res.data.self_bargain_money,
            sub_money: res.data.sub_money,
            residue_money: res.data.residue_money,
            isSelfShareMaskShow: isSelfShareMaskShow
          })

          _this.calculateScheduleWidth();
          _this.getBargainList();
        } else {
          _this.setData({
            is_self: res.data.is_self,
            other_share_num: res.data.other_share_num,
            cash: res.data.cash
          })
        }
        if (res.data.other_share_num == 1) {
          // _this.setData({
          //   isfriendShareMaskShow: 1
          // })
        }
        if (res.data.residue_money == 0) {
          _this.setData({
            is_end: 1
          })
        }

      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  // 帮助好友砍价
  helpCutPrice: function(e) {
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      order_id: _this.data.order_id,
      uid: _this.data.share_uid
    }
    app.post(helpCutPriceUrl, requestData, function(res) {
      if (res.code == 2000) {
        _this.setData({
          other_bargain_money: res.data.other_bargain_money,
          isfriendCutMaskShow: 1
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  // 砍价倒计时
  bargainCountDown: function() {
    var _this = this;
    var end_time = _this.data.end_time;
    var totalSecond = end_time - Date.parse(new Date()) / 1000;

    var interval = setInterval(function() {
      // 秒数
      var second = totalSecond;

      // 天数位
      var day = Math.floor(second / 3600 / 24);
      var dayStr = day.toString();
      if (dayStr.length == 1) dayStr = '0' + dayStr;

      // 小时位
      var hr = Math.floor((second - day * 3600 * 24) / 3600);
      var hrStr = hr.toString();
      if (hrStr.length == 1) hrStr = '0' + hrStr;

      // 分钟位
      var min = Math.floor((second - day * 3600 * 24 - hr * 3600) / 60);
      var minStr = min.toString();
      if (minStr.length == 1) minStr = '0' + minStr;

      // 秒位
      var sec = second - day * 3600 * 24 - hr * 3600 - min * 60;
      var secStr = sec.toString();
      if (secStr.length == 1) secStr = '0' + secStr;

      this.setData({
        countDownDay: dayStr,
        countDownHour: hrStr,
        countDownMinute: minStr,
        countDownSecond: secStr,
      });
      totalSecond--;
      if (totalSecond < 0) {
        clearInterval(interval);
        _this.setData({
          auction_status: 2
        })
        this.setData({
          countDownDay: '00',
          countDownHour: '00',
          countDownMinute: '00',
          countDownSecond: '00',
        });
      }
    }.bind(this), 1000);
  }
})